/*
 * @lc app=leetcode.cn id=682 lang=javascript
 *
 * [682] 棒球比赛
 */

// @lc code=start
/**
 * @param {string[]} ops
 * @return {number}
 */
var calPoints = function (ops) {
  let stack = [];

  function size() {
    return stack.length;
  }
  function empty() {
    return size() === 0;
  }
  function peek() {
    if (empty()) {
      return undefined;
    }
    return stack[size() - 1];
  }
  function push(ele) {
    stack.push(ele);
  }
  function pop() {
    return stack.pop();
  }

  function isNumber(obj) {
    return !isNaN(obj);
  }

  for (let i = 0; i < ops.length; i++) {
    const item = ops[i];

    console.log("stack", stack, " item ", item, " typeof ", isNumber(item));

    if (isNumber(item)) {
      push(parseInt(item));
    } else if (item.toUpperCase() === "C") {
      if (empty()) {
        return undefined;
      }

      pop();
    } else if (item.toUpperCase() === "D") {
      if (empty()) {
        return undefined;
      }

      push(parseInt(peek() * 2));
    } else if (item === "+") {
      if (size() < 2) {
        return undefined;
      }

      const top = pop();
      const next = top + peek();
      push(top);
      push(next);
    }
  }
  // console.log("stack", stack);
  return stack.reduce((total, current) => total + current, 0);
};
// @lc code=end
